1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.math;
18
19 import static com.google.common.math.MathBenchmarking.ARRAY_MASK;
20 import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
21 import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
22 import static com.google.common.math.MathBenchmarking.randomExponent;
23 import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
24 import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
25
26 import com.google.caliper.BeforeExperiment;
27 import com.google.caliper.Benchmark;
28 import com.google.common.math.LongMath;
29
30
31
32
33
34
35 public class LongMathBenchmark {
36 private static final int[] exponents = new int[ARRAY_SIZE];
37 private static final int[] factorialArguments = new int[ARRAY_SIZE];
38 private static final int[][] binomialArguments = new int[ARRAY_SIZE][2];
39 private static final long[] positive = new long[ARRAY_SIZE];
40 private static final long[] nonnegative = new long[ARRAY_SIZE];
41 private static final long[] longs = new long[ARRAY_SIZE];
42
43 @BeforeExperiment
44 void setUp() {
45 for (int i = 0; i < ARRAY_SIZE; i++) {
46 exponents[i] = randomExponent();
47 positive[i] = randomPositiveBigInteger(Long.SIZE - 1).longValue();
48 nonnegative[i] = randomNonNegativeBigInteger(Long.SIZE - 1).longValue();
49 longs[i] = RANDOM_SOURCE.nextLong();
50 factorialArguments[i] = RANDOM_SOURCE.nextInt(30);
51 binomialArguments[i][1] = RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials.length);
52 int k = binomialArguments[i][1];
53 binomialArguments[i][0] =
54 RANDOM_SOURCE.nextInt(MathBenchmarking.biggestBinomials[k] - k) + k;
55 }
56 }
57
58 @Benchmark int pow(int reps) {
59 int tmp = 0;
60 for (int i = 0; i < reps; i++) {
61 int j = i & ARRAY_MASK;
62 tmp += LongMath.pow(positive[j], exponents[j]);
63 }
64 return tmp;
65 }
66
67 @Benchmark int mod(int reps) {
68 int tmp = 0;
69 for (int i = 0; i < reps; i++) {
70 int j = i & ARRAY_MASK;
71 tmp += LongMath.mod(longs[j], positive[j]);
72 }
73 return tmp;
74 }
75
76 @Benchmark int gCD(int reps) {
77 int tmp = 0;
78 for (int i = 0; i < reps; i++) {
79 int j = i & ARRAY_MASK;
80 tmp += LongMath.mod(nonnegative[j], positive[j]);
81 }
82 return tmp;
83 }
84
85 @Benchmark int factorial(int reps) {
86 int tmp = 0;
87 for (int i = 0; i < reps; i++) {
88 int j = i & ARRAY_MASK;
89 tmp += LongMath.factorial(factorialArguments[j]);
90 }
91 return tmp;
92 }
93
94 @Benchmark int binomial(int reps) {
95 int tmp = 0;
96 for (int i = 0; i < reps; i++) {
97 int j = i & ARRAY_MASK;
98 tmp += LongMath.binomial(binomialArguments[j][0], binomialArguments[j][1]);
99 }
100 return tmp;
101 }
102 }